<template>
  <div class="case-creation">
    <!-- 顶部导航 -->
    <header class="bg-white shadow-sm sticky top-0 z-10">
      <div class="px-4 py-3 flex justify-between items-center">
        <h1 class="text-lg font-bold text-gray-800">案件新增</h1>
        <div class="flex items-center space-x-3">
         
        </div>
      </div>
    </header>

    <!-- 案件信息表单 -->
    <div class="form-container px-4 py-4 bg-gray-50">
      <!-- 客户状态选择 -->
      <div class="form-section bg-white rounded-xl shadow-sm p-4 mb-4">
        <h2 class="text-md font-semibold mb-3 text-gray-800 flex items-center">
          <i class="fas fa-user-check text-blue-600 mr-2"></i>客户状态
        </h2>
        
        <div class="grid grid-cols-2 gap-3">
          <label class="client-status-option">
            <input type="radio" v-model="caseForm.clientStatus" value="signed" class="sr-only">
            <div :class="['status-card p-4 border-2 rounded-lg text-center cursor-pointer transition-all',
                         caseForm.clientStatus === 'signed' ? 'border-blue-500 bg-blue-50' : 'border-gray-200 hover:border-gray-300']">
              <i class="fas fa-file-signature text-2xl mb-2" 
                 :class="caseForm.clientStatus === 'signed' ? 'text-blue-600' : 'text-gray-400'"></i>
              <div class="text-sm font-medium" 
                   :class="caseForm.clientStatus === 'signed' ? 'text-blue-700' : 'text-gray-600'">
                已签约客户
              </div>
            </div>
          </label>
          
          <label class="client-status-option">
            <input type="radio" v-model="caseForm.clientStatus" value="pending" class="sr-only">
            <div :class="['status-card p-4 border-2 rounded-lg text-center cursor-pointer transition-all',
                         caseForm.clientStatus === 'pending' ? 'border-orange-500 bg-orange-50' : 'border-gray-200 hover:border-gray-300']">
              <i class="fas fa-hourglass-half text-2xl mb-2" 
                 :class="caseForm.clientStatus === 'pending' ? 'text-orange-600' : 'text-gray-400'"></i>
              <div class="text-sm font-medium" 
                   :class="caseForm.clientStatus === 'pending' ? 'text-orange-700' : 'text-gray-600'">
                待签约客户
              </div>
            </div>
          </label>
        </div>
      </div>



      <!-- 材料上传 -->
      <div class="form-section bg-white rounded-xl shadow-sm p-4 mb-4">
        <h2 class="text-md font-semibold mb-3 text-gray-800 flex items-center cursor-pointer" @click="uploadExpanded = !uploadExpanded">
          <i class="fas fa-upload text-blue-600 mr-2"></i>材料上传
          <i :class="['fas', 'ml-auto', 'text-gray-400', 'transition-transform', uploadExpanded ? 'fa-chevron-up' : 'fa-chevron-down']"></i>
        </h2>
        
        <div v-show="uploadExpanded">
        <!-- 身份材料 -->
        <div class="upload-section mb-4">
          <h3 class="text-sm font-medium mb-2 text-gray-700">身份材料</h3>
          <div class="upload-area border-2 border-dashed border-gray-300 rounded-lg p-4 text-center hover:border-blue-500 transition-colors">
            <i class="fas fa-id-card text-2xl text-gray-400 mb-2"></i>
            <p class="text-gray-600 mb-1 text-sm">上传身份证、户口本等身份证明</p>
            <p class="text-xs text-gray-500">支持 JPG、PNG、PDF</p>
            <input 
              type="file" 
              multiple 
              accept=".jpg,.jpeg,.png,.pdf"
              @change="handleIdentityUpload"
              class="hidden"
              ref="identityInput"
            >
            <button 
              @click="$refs.identityInput.click()"
              class="mt-2 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors text-sm"
            >
              选择文件
            </button>
          </div>
          
          <!-- 已上传的身份文件 -->
          <div v-if="uploadedIdentity.length > 0" class="mt-4">
            <div v-for="(file, index) in uploadedIdentity" :key="index" class="flex items-center justify-between p-3 bg-gray-50 rounded-lg mb-2">
              <div class="flex items-center">
                <i class="fas fa-file-alt text-blue-500 mr-2"></i>
                <span class="text-sm">{{ file.name }}</span>
              </div>
              <button @click="removeIdentityFile(index)" class="text-red-500 hover:text-red-700">
                <i class="fas fa-trash"></i>
              </button>
            </div>
          </div>
        </div>

        
        <!-- 医疗材料 -->
        <div class="upload-section mb-6">
          <h3 class="text-md font-medium mb-3 text-gray-700">医疗材料</h3>
          <div class="upload-area border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-blue-500 transition-colors">
            <i class="fas fa-stethoscope text-3xl text-gray-400 mb-2"></i>
            <p class="text-gray-600 mb-2">上传医疗诊断证明、病历等材料</p>
            <input 
              type="file" 
              multiple 
              accept=".jpg,.jpeg,.png,.pdf"
              @change="handleMedicalUpload"
              class="hidden"
              ref="medicalInput"
            >
            <button 
              @click="$refs.medicalInput.click()"
              class="mt-3 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
            >
              选择文件
            </button>
          </div>
          
          <!-- 已上传的医疗文件 -->
          <div v-if="uploadedMedical.length > 0" class="mt-4">
            <div v-for="(file, index) in uploadedMedical" :key="index" class="flex items-center justify-between p-3 bg-gray-50 rounded-lg mb-2">
              <div class="flex items-center">
                <i class="fas fa-file-alt text-blue-500 mr-2"></i>
                <span class="text-sm">{{ file.name }}</span>
              </div>
              <button @click="removeMedicalFile(index)" class="text-red-500 hover:text-red-700">
                <i class="fas fa-trash"></i>
              </button>
            </div>
          </div>
        </div>
        
        <!-- 事故责任认定书 -->
        <div class="upload-section mb-6">
          <h3 class="text-md font-medium mb-3 text-gray-700">事故责任认定书</h3>
          <div class="upload-area border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-blue-500 transition-colors">
            <i class="fas fa-file-alt text-3xl text-gray-400 mb-2"></i>
            <p class="text-gray-600 mb-2">上传事故责任认定书</p>
            <input 
              type="file" 
              accept=".jpg,.jpeg,.png,.pdf"
              @change="handleAccidentReportUpload"
              class="hidden"
              ref="accidentReportInput"
            >
            <button 
              @click="$refs.accidentReportInput.click()"
              class="mt-3 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
            >
              选择文件
            </button>
          </div>
          
          <div v-if="accidentReport" class="mt-4 flex items-center justify-between p-3 bg-gray-50 rounded-lg">
            <div class="flex items-center">
              <i class="fas fa-file-alt text-blue-500 mr-2"></i>
              <span class="text-sm">{{ accidentReport.name }}</span>
            </div>
            <button @click="removeAccidentReport" class="text-red-500 hover:text-red-700">
              <i class="fas fa-trash"></i>
            </button>
          </div>
        </div>
        
        <!-- 其他材料 -->
        <div class="upload-section">
          <h3 class="text-md font-medium mb-3 text-gray-700">其他材料</h3>
          <div class="upload-area border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-blue-500 transition-colors">
            <i class="fas fa-folder text-3xl text-gray-400 mb-2"></i>
            <p class="text-gray-600 mb-2">上传其他相关材料</p>
            <input 
              type="file" 
              multiple 
              accept=".jpg,.jpeg,.png,.pdf"
              @change="handleOtherUpload"
              class="hidden"
              ref="otherInput"
            >
            <button 
              @click="$refs.otherInput.click()"
              class="mt-3 bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition-colors"
            >
              选择文件
            </button>
          </div>
          
          <!-- 已上传的其他文件 -->
          <div v-if="uploadedOthers.length > 0" class="mt-4">
            <div v-for="(file, index) in uploadedOthers" :key="index" class="flex items-center justify-between p-3 bg-gray-50 rounded-lg mb-2">
              <div class="flex items-center">
                <i class="fas fa-file-alt text-blue-500 mr-2"></i>
                <span class="text-sm">{{ file.name }}</span>
              </div>
              <button @click="removeOtherFile(index)" class="text-red-500 hover:text-red-700">
                <i class="fas fa-trash"></i>
              </button>
            </div>
          </div>
        </div>
        </div>
      </div>

      <!-- 基本信息 -->
      <div class="form-section bg-white rounded-xl shadow-sm p-4 mb-4">
        <div class="flex items-center justify-between mb-3 cursor-pointer" @click="toggleBasicInfo">
          <h2 class="text-md font-semibold text-gray-800 flex items-center">
          <i class="fas fa-info-circle text-blue-600 mr-2"></i>基本信息
        </h2>
          <i :class="['fas transition-transform', basicInfoExpanded ? 'fa-chevron-up' : 'fa-chevron-down']"></i>
        </div>
        
        <div v-show="basicInfoExpanded" class="basic-info-content">
        
        <div class="space-y-4">
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">案件编号</label>
            <input 
              v-model="caseForm.caseNumber" 
              type="text" 
              class="w-full px-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入案件编号"
            >
          </div>
          
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">案件类型</label>
            <select 
              v-model="caseForm.caseType" 
              class="w-full px-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            >
              <option value="">请选择案件类型</option>
              <option value="traffic-accident">交通事故</option>
              <option value="personal-injury">人损</option>
              <option value="accident-insurance">意外险</option>
              <option value="work-injury">工伤（职伤）</option>
            </select>
          </div>
          

          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">事故日期</label>
            <input 
              v-model="caseForm.accidentDate" 
              type="date" 
              class="w-full px-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            >
          </div>
          
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">事故地点</label>
            <input 
              v-model="caseForm.accidentLocation" 
              type="text" 
              class="w-full px-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入详细事故地点"
            >
          </div>
          
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">交警部门</label>
            <input 
              v-model="caseForm.policeStation" 
              type="text" 
              class="w-full px-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入负责的交警部门"
            >
          </div>
          
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">事故认定书编号</label>
            <input 
              v-model="caseForm.accidentReportNo" 
              type="text" 
              class="w-full px-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入事故认定书编号"
            >
          </div>
          
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">责任比例</label>
            <select 
              v-model="caseForm.liabilityRatio" 
              class="w-full px-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            >
              <option value="">请选择责任比例</option>
              <option value="100-0">对方全责</option>
              <option value="0-100">我方全责</option>
              <option value="70-30">对方主责(70%)</option>
              <option value="30-70">我方主责(70%)</option>
              <option value="50-50">同等责任</option>
              <option value="pending">待定</option>
            </select>
          </div>
          </div>
        </div>
      </div>

      <!-- 当事人信息 -->
      <div class="form-section bg-white rounded-xl shadow-sm p-4 mb-4">
        <div class="flex items-center justify-between mb-3 cursor-pointer" @click="toggleClientInfo">
          <h2 class="text-md font-semibold text-gray-800 flex items-center">
          <i class="fas fa-user text-blue-600 mr-2"></i>当事人信息
        </h2>
          <i :class="['fas transition-transform', clientInfoExpanded ? 'fa-chevron-up' : 'fa-chevron-down']"></i>
        </div>
        
        <div v-show="clientInfoExpanded" class="client-info-content">
        
        <div class="space-y-4">
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">姓名</label>
            <input 
              v-model="caseForm.clientName" 
              type="text" 
              class="w-full px-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入当事人姓名"
            >
          </div>
          
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">身份证号</label>
            <input 
              v-model="caseForm.clientIdCard" 
              type="text" 
              class="w-full px-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入身份证号"
            >
          </div>
          
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">联系电话</label>
            <input 
              v-model="caseForm.clientPhone" 
              type="tel" 
              class="w-full px-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入联系电话"
            >
          </div>
          
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">联系地址</label>
            <input 
              v-model="caseForm.clientAddress" 
              type="text" 
              class="w-full px-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入联系地址"
            >
          </div>
          
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">职业</label>
            <input 
              v-model="caseForm.clientOccupation" 
              type="text" 
              class="w-full px-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入职业"
            >
          </div>
          
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">月收入</label>
            <input 
              v-model="caseForm.clientIncome" 
              type="number" 
              class="w-full px-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入月收入"
            >
          </div>
          
          <div class="form-group">
            <label class="block text-sm font-medium text-gray-700 mb-2">家庭成员</label>
            <input 
              v-model="caseForm.clientFamily" 
              type="text" 
              class="w-full px-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              placeholder="请输入家庭成员"
            >
          </div>
        </div>
      </div>
          </div>
      
      <!-- 案情备注 -->
      <div class="form-section bg-white rounded-xl shadow-sm p-4 mb-4">
        <h2 class="text-md font-semibold mb-3 text-gray-800 flex items-center">
          <i class="fas fa-tags text-blue-600 mr-2"></i>案情备注
        </h2>
        
        <div class="flex flex-wrap gap-2">
          <label v-for="tag in caseNoteTags" :key="tag.value" class="case-note-tag">
            <input type="checkbox" v-model="caseForm.selectedCaseNoteTags" :value="tag.value" class="sr-only">
            <div :class="['tag-option px-3 py-2 border-2 rounded-lg text-sm cursor-pointer transition-all',
                         caseForm.selectedCaseNoteTags.includes(tag.value) ? 
                         'border-blue-500 bg-blue-50 text-blue-700' : 
                         'border-gray-200 text-gray-600 hover:border-gray-300']">
              <i :class="tag.icon" class="mr-1"></i>
              {{ tag.label }}
            </div>
          </label>
        </div>
      </div>
          </div>
          
    <!-- 操作按钮 -->
    <div class="fixed top-4 right-4 z-10">
      <div class="flex space-x-3">
        <button @click="saveDraft" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 font-medium bg-white shadow-sm hover:bg-gray-50">
          <i class="fas fa-save mr-2"></i>保存
            </button>
        <button @click="convertToSigned" class="px-4 py-2 bg-blue-600 text-white rounded-lg font-medium shadow-sm hover:bg-blue-700">
          <i class="fas fa-arrow-right mr-2"></i>转签约
              </button>
            </div>
          </div>
        </div>
        
  <!-- 悬浮备忘录按钮 -->
  <div class="fixed top-20 right-6 z-50">
    <div class="relative">
      <button 
        @click="toggleFloatingMemo"
        class="bg-blue-600 hover:bg-blue-700 text-white rounded-full p-3 shadow-lg transition-colors duration-200 flex flex-col items-center justify-center min-w-[70px] min-h-[70px]"
        title="备忘录（仅本人可见）"
      >
        <i class="fas fa-sticky-note text-lg mb-1"></i>
        <span class="text-xs font-medium">备忘录</span>
      </button>
      <!-- 提醒数字徽章 -->
      <div 
        v-if="totalReminderCount > 0" 
        class="absolute -top-2 -right-2 bg-red-500 text-white text-xs font-bold rounded-full min-w-[20px] h-5 flex items-center justify-center px-1 shadow-lg"
      >
        {{ totalReminderCount > 99 ? '99+' : totalReminderCount }}
      </div>
    </div>
  </div>
          
  <!-- 悬浮备忘录弹窗 -->
  <div v-if="showFloatingMemo" class="fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center p-4">
    <div class="bg-white rounded-xl shadow-2xl w-full max-w-2xl max-h-[85vh] overflow-hidden">
      <!-- 弹窗头部 -->
      <div class="bg-blue-600 text-white p-4 flex items-center justify-between">
        <div class="flex items-center">
          <i class="fas fa-sticky-note mr-2"></i>
          <h3 class="text-lg font-semibold">备忘录（仅本人可见）</h3>
        </div>
        <button @click="closeFloatingMemo" class="text-white hover:text-gray-200">
          <i class="fas fa-times text-xl"></i>
        </button>
      </div>
        
      <!-- 弹窗内容 -->
      <div class="p-6 overflow-y-auto max-h-[70vh]">
        <!-- 设备总事项 -->
        <div class="mb-6">
          <label class="block text-sm font-medium text-gray-700 mb-2">设备总事项</label>
          <textarea 
            v-model="caseForm.equipmentNotes" 
            rows="3" 
            class="w-full px-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            placeholder="记录设备相关的重要事项..."
          ></textarea>
        </div>
        
        <!-- 医院情况 -->
        <div class="mb-6">
          <label class="block text-sm font-medium text-gray-700 mb-2">医院情况</label>
          <textarea 
            v-model="caseForm.hospitalInfo" 
            rows="3" 
            class="w-full px-3 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
            placeholder="记录医院相关情况..."
          ></textarea>
        </div>
        
        <!-- 案件备忘 -->
        <div class="mb-6">
          <label class="block text-sm font-medium text-gray-700 mb-2">案件备忘</label>
          <div class="space-y-3">
            <div class="flex space-x-2">
              <input 
                v-model="newNote" 
                type="text" 
                class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="添加新的备忘事项..."
                @keypress.enter="addNote"
              >
              <button 
                @click="addNote" 
                class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
              >
                <i class="fas fa-plus"></i>
              </button>
            </div>
            
            <div class="space-y-2 max-h-40 overflow-y-auto">
              <div v-if="caseForm.memoNotes.length === 0" class="text-gray-500 text-center py-4">
                暂无案件备忘
              </div>
              <div v-for="(note, index) in caseForm.memoNotes" :key="index" 
                   class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                <div class="flex items-center space-x-3">
                  <i class="fas fa-sticky-note text-blue-500"></i>
                  <span class="text-sm text-gray-700">{{ note.content }}</span>
                </div>
                <div class="flex items-center space-x-2">
                  <span class="text-xs text-gray-500">{{ note.time }}</span>
                  <button @click="removeNote(index)" class="text-red-500 hover:text-red-700">
                    <i class="fas fa-trash text-xs"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 提醒事项 -->
        <div class="mb-4">
          <label class="block text-sm font-medium text-gray-700 mb-2">提醒事项</label>
          <div class="space-y-3">
            <div class="flex space-x-2">
              <input 
                v-model="newReminder.content" 
                type="text" 
                class="flex-1 px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                placeholder="提醒内容..."
              >
              <input 
                v-model="newReminder.time" 
                type="datetime-local" 
                class="px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
              >
              <button 
                @click="addReminder" 
                class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition-colors"
              >
                <i class="fas fa-bell"></i>
              </button>
            </div>
            
            <div class="space-y-2 max-h-40 overflow-y-auto">
              <div v-if="caseForm.reminders.length === 0" class="text-gray-500 text-center py-4">
                暂无提醒事项
              </div>
              <div v-for="(reminder, index) in caseForm.reminders" :key="index" 
                   class="flex items-center justify-between p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
                <div class="flex items-center space-x-3">
                  <i class="fas fa-bell text-yellow-600"></i>
                  <span class="text-sm text-gray-700">{{ reminder.content }}</span>
                </div>
                <div class="flex items-center space-x-2">
                  <span class="text-xs text-gray-500">{{ formatTime(reminder.time) }}</span>
                  <button @click="removeReminder(index)" class="text-red-500 hover:text-red-700">
                    <i class="fas fa-trash text-xs"></i>
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 弹窗底部 -->
      <div class="border-t p-4 bg-gray-50">
        <div class="flex justify-between items-center text-sm text-gray-600">
          <span>备忘录: {{ caseForm.memoNotes.length }} 条 | 提醒: {{ caseForm.reminders.length }} 条</span>
          <button 
            @click="closeFloatingMemo"
            class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
          >
            完成
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, nextTick, computed } from 'vue'
import { useRouter } from 'vue-router'
import { caseApi } from '@/api/case'

export default {
  name: 'CaseCreation',
  setup() {
    const router = useRouter()
    
    // 表单数据
    const caseForm = reactive({
      caseNumber: 'AL2024010001',
      caseType: 'traffic_accident',
      clientStatus: 'signed',
      selectedCaseNoteTags: ['disability', 'medical-advance'],
      memoNotes: [
        {
          content: '客户存在轻微伤残，需要进行专业鉴定',
          time: '2024-01-15 14:30'
        },
        {
          content: '对方保险公司已联系，预计赔付金额待商议',
          time: '2024-01-16 09:15'
        },
        {
          content: '医疗费用单据需要整理完毕，缺少部分发票',
          time: '2024-01-16 16:45'
        }
      ],
      accidentDate: '2024-01-10',
      accidentLocation: '北京市朝阳区建国路与东三环交叉口',
      policeStation: '朝阳区交警支队建国路中队',
      accidentReportNo: 'BJ20240110001',
      liabilityRatio: '对方全责',
      clientName: '张明华',
      clientIdCard: '110101199001011234',
      clientPhone: '13812345678',
      clientAddress: '北京市朝阳区望京街道阜通东大街1号',
      clientOccupation: '软件工程师',
      clientIncome: '月收入15000元',
      clientFamily: '已婚，配偶李女士，育有一子8岁',
      equipmentNotes: '事故车辆为2020年本田雅阁，车损严重，前保险杠完全损坏，需要更换。发动机舱轻微变形，但不影响正常使用。车辆已送至指定维修厂进行维修评估。预计维修费用8万元左右。',
      hospitalInfo: '患者目前在北京协和医院骨科住院治疗，主治医生为李主任。预计住院时间2-3周，康复期约3个月。医院已出具诊断证明，建议定期复查。目前医疗费用已花费2.8万元。',
      wardInfo: '骨科病房3楼308床，病房环境良好，有专门的护理人员',
      caregiverInfo: '配偶李女士全程陪护，已请假一个月专门照料',
      reminders: [
        {
          content: '提醒客户下周三去医院复查',
          time: '2024-01-24T10:00',
          date: '2024-01-24T10:00'
        },
        {
          content: '整理并提交医疗费用清单给保险公司',
          time: '2024-01-22T14:00',
          date: '2024-01-22T14:00'
        },
        {
          content: '联系交警部门确认事故责任认定书进度',
          time: '2024-01-25T09:30',
          date: '2024-01-25T09:30'
        }
      ]
    })
    
    // 新增备忘录相关变量
    const newNote = ref('')
    const newReminder = reactive({
      content: '',
      time: ''
    })

    // 悬浮备忘录相关变量
    const showFloatingMemo = ref(false)
    const quickMemoInput = ref('')
    
    // 配案商数据
    const partnerFirms = ref([
      {
        id: 1,
        name: '金诚律师事务所',
        logo: 'https://via.placeholder.com/48x48?text=金',
        rating: 4.8,
        goodReviewRate: 95,
        successCases: 156,
        salesVolume: 203,
        excellentLawyers: ['张律师', '李律师', '王律师'],
        location: '北京市朝阳区'
      },
      {
        id: 2,
        name: '华信法律咨询',
        logo: 'https://via.placeholder.com/48x48?text=华',
        rating: 4.6,
        goodReviewRate: 92,
        successCases: 132,
        salesVolume: 178,
        excellentLawyers: ['陈律师', '刘律师'],
        location: '北京市海淀区'
      },
      {
        id: 3,
        name: '正义律师团队',
        logo: 'https://via.placeholder.com/48x48?text=正',
        rating: 4.9,
        goodReviewRate: 97,
        successCases: 89,
        salesVolume: 124,
        excellentLawyers: ['赵律师', '孙律师', '周律师'],
        location: '北京市西城区'
      }
    ])
    
    const selectedPartner = ref({
      id: 1,
      name: '金诚律师事务所',
      logo: 'https://via.placeholder.com/48x48?text=金',
      rating: 4.8,
      goodReviewRate: 95,
      successCases: 156,
      salesVolume: 203,
      excellentLawyers: ['张律师', '李律师', '王律师'],
      location: '北京市朝阳区'
    })
    
    // 案情备注标签
    const caseNoteTags = ref([
      { value: 'disability', label: '伤残', icon: 'fas fa-wheelchair' },
      { value: 'negotiation', label: '和谈', icon: 'fas fa-handshake' },
      { value: 'double-compensation', label: '误工双赔', icon: 'fas fa-coins' },
      { value: 'medical-advance', label: '医疗费垫付', icon: 'fas fa-credit-card' }
    ])
    
    // 折叠状态
    const basicInfoExpanded = ref(false)
    const clientInfoExpanded = ref(false)
    const memoExpanded = ref(false)
    const uploadExpanded = ref(false)
    
    // 文件上传
    const uploadedIdentity = ref([
      { name: '身份证正面.jpg', size: '1.2MB', type: 'image/jpeg' },
      { name: '身份证反面.jpg', size: '1.1MB', type: 'image/jpeg' },
      { name: '驾驶证.jpg', size: '0.8MB', type: 'image/jpeg' }
    ])
    const accidentReport = ref({ 
      name: '道路交通事故认定书.pdf', 
      size: '2.3MB', 
      type: 'application/pdf' 
    })
    const uploadedMedical = ref([
      { name: '医院诊断证明.pdf', size: '1.5MB', type: 'application/pdf' },
      { name: '医疗费用清单.xlsx', size: '0.6MB', type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' },
      { name: 'CT检查报告.jpg', size: '2.1MB', type: 'image/jpeg' },
      { name: '住院病历.pdf', size: '3.2MB', type: 'application/pdf' }
    ])
    const uploadedOthers = ref([
      { name: '车辆维修评估报告.pdf', size: '1.8MB', type: 'application/pdf' },
      { name: '保险公司定损单.jpg', size: '1.3MB', type: 'image/jpeg' },
      { name: '现场照片1.jpg', size: '2.5MB', type: 'image/jpeg' },
      { name: '现场照片2.jpg', size: '2.2MB', type: 'image/jpeg' }
    ])
    
    // 配案商选择
    const selectPartner = (partner) => {
      selectedPartner.value = partner
    }
    
    // 折叠控制
    const toggleBasicInfo = () => {
      basicInfoExpanded.value = !basicInfoExpanded.value
    }
    
    const toggleClientInfo = () => {
      clientInfoExpanded.value = !clientInfoExpanded.value
    }
    
    // 备忘录管理
    const addNote = () => {
      if (newNote.value.trim()) {
        const now = new Date()
        caseForm.memoNotes.push({
          content: newNote.value.trim(),
          time: now.toLocaleDateString('zh-CN', { 
            month: '2-digit', 
            day: '2-digit',
            hour: '2-digit', 
            minute: '2-digit' 
          })
        })
        newNote.value = ''
      }
    }
    
    const removeNote = (index) => {
      caseForm.memoNotes.splice(index, 1)
    }
    
    // 提醒管理
    const addReminder = () => {
      if (newReminder.content.trim() && newReminder.time) {
        caseForm.reminders.push({
          content: newReminder.content.trim(),
          time: newReminder.time,
          date: newReminder.time
        })
        newReminder.content = ''
        newReminder.time = ''
      }
    }
    
    const removeReminder = (index) => {
      caseForm.reminders.splice(index, 1)
    }
    
    // 格式化时间显示
    const formatTime = (timeString) => {
      if (!timeString) return ''
      const date = new Date(timeString)
      return date.toLocaleDateString('zh-CN', {
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    // 悬浮备忘录相关方法
    const toggleFloatingMemo = () => {
      showFloatingMemo.value = !showFloatingMemo.value
      if (showFloatingMemo.value) {
        nextTick(() => {
          document.querySelector('.quick-memo-input')?.focus()
        })
      }
    }

    const addQuickMemo = () => {
      if (quickMemoInput.value.trim()) {
        const now = new Date()
        caseForm.memoNotes.push({
          content: quickMemoInput.value.trim(),
          time: now.toLocaleDateString('zh-CN', { 
            month: '2-digit', 
            day: '2-digit',
            hour: '2-digit', 
            minute: '2-digit' 
          })
        })
        quickMemoInput.value = ''
        // 不自动关闭弹窗，让用户可以继续添加
      }
    }

    const removeQuickMemo = (index) => {
      caseForm.memoNotes.splice(index, 1)
    }

    const closeFloatingMemo = () => {
      showFloatingMemo.value = false
      quickMemoInput.value = ''
    }

    const cancelQuickMemo = () => {
      quickMemoInput.value = ''
      showFloatingMemo.value = false
    }
    
    // 文件上传处理
    const handleIdentityUpload = (event) => {
      const files = Array.from(event.target.files)
      uploadedIdentity.value.push(...files)
    }
    

    
    const handleAccidentReportUpload = (event) => {
      const file = event.target.files[0]
      if (file) {
        accidentReport.value = file
      }
    }
    
    const handleMedicalUpload = (event) => {
      const files = Array.from(event.target.files)
      uploadedMedical.value.push(...files)
    }
    
    const handleOtherUpload = (event) => {
      const files = Array.from(event.target.files)
      uploadedOthers.value.push(...files)
    }
    
    // 删除文件
    const removeIdentityFile = (index) => {
      uploadedIdentity.value.splice(index, 1)
    }
    

    
    const removeAccidentReport = () => {
      accidentReport.value = null
    }
    
    const removeMedicalFile = (index) => {
      uploadedMedical.value.splice(index, 1)
    }
    
    const removeOtherFile = (index) => {
      uploadedOthers.value.splice(index, 1)
    }
    
    // 转签约功能
    const convertToSigned = () => {
      if (!caseForm.clientName || !caseForm.clientPhone) {
        alert('请先完善客户基本信息')
        return
      }
      
      if (!caseForm.caseType) {
        alert('请先选择案件类型')
        return
      }
      
      // 准备传递给签约页面的数据
      const caseData = {
        // 基本信息
        caseNumber: caseForm.caseNumber,
        caseType: caseForm.caseType,
        clientName: caseForm.clientName,
        clientPhone: caseForm.clientPhone,
        
        // 当事人信息
        clientIdCard: caseForm.clientIdCard,
        clientAddress: caseForm.clientAddress,
        clientAge: caseForm.clientAge,
        clientGender: caseForm.clientGender,
        clientOccupation: caseForm.clientOccupation,
        clientEducation: caseForm.clientEducation,
        clientMaritalStatus: caseForm.clientMaritalStatus,
        clientIncome: caseForm.clientIncome,
        
        // 案件信息
        accidentDate: caseForm.accidentDate,
        accidentLocation: caseForm.accidentLocation,
        accidentDescription: caseForm.accidentDescription,
        injuryDescription: caseForm.injuryDescription,
        
        // 备忘录信息
        equipmentNotes: caseForm.equipmentNotes,
        hospitalInfo: caseForm.hospitalInfo,
        selectedCaseNoteTags: caseForm.selectedCaseNoteTags,
        memoNotes: caseForm.memoNotes,
        reminderTags: caseForm.reminderTags
      }
      
      // 跳转到签约页面，传递案件数据
      router.push({
        name: 'MarketingContractSigning',
        query: {
          caseData: encodeURIComponent(JSON.stringify(caseData))
        }
      })
    }
    
    // 保存草稿
    const saveDraft = async () => {
      try {
        const formData = new FormData()
        
        // 添加基本信息
        Object.keys(caseForm).forEach(key => {
          formData.append(key, caseForm[key])
        })
        
        // 添加文件

        
        if (accidentReport.value) {
          formData.append('accidentReport', accidentReport.value)
        }
        
        uploadedMedical.value.forEach(file => {
          formData.append('medical', file)
        })
        
        uploadedOthers.value.forEach(file => {
          formData.append('others', file)
        })
        
        await caseApi.createCase(formData)
        alert('草稿保存成功')
      } catch (error) {
        console.error('保存草稿失败:', error)
        alert('保存草稿失败')
      }
    }
    
    // 提交案件
    const submitCase = async () => {
      try {
        // 验证必填字段
        if (!caseForm.caseNumber || !caseForm.clientName || !caseForm.clientPhone) {
          alert('请填写必填字段')
          return
        }
        
        const formData = new FormData()
        
        // 添加基本信息
        Object.keys(caseForm).forEach(key => {
          formData.append(key, caseForm[key])
        })
        
        // 添加文件

        
        if (accidentReport.value) {
          formData.append('accidentReport', accidentReport.value)
        }
        
        uploadedMedical.value.forEach(file => {
          formData.append('medical', file)
        })
        
        uploadedOthers.value.forEach(file => {
          formData.append('others', file)
        })
        
        await caseApi.createCase(formData)
        alert('案件提交成功')
        router.push('/marketing/cases')
      } catch (error) {
        console.error('提交案件失败:', error)
        alert('提交案件失败')
      }
    }
    
    // 计算总的提醒数量
    const totalReminderCount = computed(() => {
      return caseForm.memoNotes.length + caseForm.reminders.length
    })
    
    return {
      caseForm,
      partnerFirms,
      selectedPartner,
      caseNoteTags,
      basicInfoExpanded,
      clientInfoExpanded,
      memoExpanded,
      uploadExpanded,
      uploadedIdentity,

      accidentReport,
      uploadedMedical,
      uploadedOthers,
      newNote,
      newReminder,
      selectPartner,
      toggleBasicInfo,
      toggleClientInfo,
      addNote,
      removeNote,
      addReminder,
      removeReminder,
      formatTime,
      handleIdentityUpload,

      handleAccidentReportUpload,
      handleMedicalUpload,
      handleOtherUpload,
      removeIdentityFile,

      removeAccidentReport,
      removeMedicalFile,
      removeOtherFile,
      convertToSigned,
      saveDraft,
      submitCase,
      // 悬浮备忘录相关
      showFloatingMemo,
      quickMemoInput,
      toggleFloatingMemo,
      addQuickMemo,
      removeQuickMemo,
      closeFloatingMemo,
      cancelQuickMemo,
      // 计算属性
      totalReminderCount
    }
  }
}
</script>

<style scoped>
.upload-area {
  transition: all 0.3s ease;
}

.upload-area:hover {
  border-color: #3b82f6;
  background-color: #f8fafc;
}

.form-group {
  margin-bottom: 1rem;
}

.form-section {
  margin-bottom: 1.5rem;
}
</style> 